import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtGraphicalEffects 1.12

Rectangle {
    id: registerPage
    anchors.fill: parent
    color: "#f5f7fa"
    
    // 信号定义
    signal switchToLogin()
    
    // 属性
    property bool isLoading: false
    property string statusMessage: ""
    property string statusColor: "#e74c3c"
    
    // 连接AuthManager信号
    Connections {
        target: authManager
        
        onRegistrationSuccess: {
            console.log("RegisterPage: ===== Received registrationSuccess signal =====")
            console.log("RegisterPage: Message:", message)
            console.log("RegisterPage: isLoading before:", registerPage.isLoading)
            registerPage.isLoading = false
            console.log("RegisterPage: isLoading after:", registerPage.isLoading)
            registerPage.statusMessage = message
            registerPage.statusColor = "#27ae60"
            statusTimer.start()
            console.log("RegisterPage: Starting timers...")
            registerSuccessTimer.start()
            console.log("RegisterPage: Timers started, will emit switchToLogin in 2 seconds")
        }
        
        onRegistrationFailed: {
            console.log("RegisterPage: ===== Received registrationFailed signal =====")
            console.log("RegisterPage: Error:", error)
            registerPage.isLoading = false
            registerPage.statusMessage = error
            registerPage.statusColor = "#e74c3c"
            statusTimer.start()
        }
    }
    
    // 状态消息定时器
    Timer {
        id: statusTimer
        interval: 4000
        onTriggered: registerPage.statusMessage = ""
    }
    
    // 注册成功延迟跳转定时器
    Timer {
        id: registerSuccessTimer
        interval: 2000
        onTriggered: {
            console.log("RegisterPage: emit switchToLogin for page pop")
            registerPage.switchToLogin()
        }
    }
    
    // 组件初始化检查
    Component.onCompleted: {
        console.log("RegisterPage: Component completed")
        console.log("RegisterPage: authManager available?", authManager !== undefined)
        if (authManager !== undefined) {
            console.log("RegisterPage: authManager is valid")
            console.log("RegisterPage: authManager type:", typeof authManager)
            console.log("RegisterPage: authManager.isLoggedIn:", authManager.isLoggedIn)
            
            // 测试信号连接
            console.log("RegisterPage: Testing signal connection...")
        } else {
            console.error("RegisterPage: ERROR - authManager is undefined!")
        }
    }
    
    // 背景装饰
    Rectangle {
        anchors.fill: parent
        gradient: Gradient {
            GradientStop { position: 0.0; color: "#764ba2" }
            GradientStop { position: 1.0; color: "#667eea" }
        }
    }
    
    // 几何装饰元素
    Item {
        anchors.fill: parent
        
        // 装饰圆圈1
        Rectangle {
            width: 250
            height: 250
            radius: 125
            color: "#ffffff15"
            anchors.left: parent.left
            anchors.top: parent.top
            anchors.leftMargin: -80
            anchors.topMargin: -80
        }
        
        // 装饰圆圈2
        Rectangle {
            width: 180
            height: 180
            radius: 90
            color: "#ffffff20"
            anchors.right: parent.right
            anchors.bottom: parent.bottom
            anchors.rightMargin: -50
            anchors.bottomMargin: -50
        }
    }
    
    // 主注册卡片
    Rectangle {
        id: registerCard
        width: 420
        height: 650
        anchors.centerIn: parent
        color: "white"
        radius: 20
        
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 8
            radius: 20
            samples: 40
            color: "#40000000"
        }
        
        ScrollView {
            anchors.fill: parent
            anchors.margins: 40
            clip: true
            
            ColumnLayout {
                width: registerCard.width - 80
                spacing: 20
                
                // 系统标题
                ColumnLayout {
                    Layout.alignment: Qt.AlignHCenter
                    spacing: 10
                    
                    // Logo占位
                    Rectangle {
                        width: 80
                        height: 80
                        radius: 40
                        color: "#764ba2"
                        Layout.alignment: Qt.AlignHCenter
                        
                        Text {
                            anchors.centerIn: parent
                            text: "🌾"
                            font.pixelSize: 40
                            color: "white"
                        }
                    }
                    
                    Text {
                        text: "甘蔗农机智能管控平台"
                        font.pixelSize: 22
                        font.bold: true
                        color: "#2c3e50"
                        Layout.alignment: Qt.AlignHCenter
                    }
                    
                    Text {
                        text: "创建您的账户"
                        font.pixelSize: 14
                        color: "#7f8c8d"
                        Layout.alignment: Qt.AlignHCenter
                    }
                }
                
                // 注册表单
                ColumnLayout {
                    Layout.fillWidth: true
                    spacing: 18
                    
                    // 用户名输入
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 5
                        
                        Text {
                            text: "用户名"
                            font.pixelSize: 14
                            color: "#34495e"
                            font.bold: true
                        }
                        
                        Rectangle {
                            Layout.fillWidth: true
                            height: 50
                            color: "#f8f9fa"
                            border.color: usernameField.activeFocus ? "#764ba2" : "#e9ecef"
                            border.width: 2
                            radius: 8
                            
                            RowLayout {
                                anchors.fill: parent
                                anchors.margins: 15
                                spacing: 10
                                
                                Text {
                                    text: "👤"
                                    font.pixelSize: 16
                                    color: "#7f8c8d"
                                }
                                
                                TextField {
                                    id: usernameField
                                    Layout.fillWidth: true
                                    placeholderText: "3-20个字符，字母数字下划线"
                                    font.pixelSize: 14
                                    color: "#2c3e50"
                                    background: Rectangle { color: "transparent" }
                                    selectByMouse: true
                                    
                                    Keys.onReturnPressed: emailField.focus = true
                                }
                            }
                        }
                        
                        // 用户名验证提示
                        Text {
                            text: getUsernameHint()
                            font.pixelSize: 11
                            color: getUsernameHintColor()
                            visible: usernameField.text.length > 0
                            Layout.topMargin: -2
                        }
                    }
                    
                    // 邮箱输入
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 5
                        
                        Text {
                            text: "邮箱地址"
                            font.pixelSize: 14
                            color: "#34495e"
                            font.bold: true
                        }
                        
                        Rectangle {
                            Layout.fillWidth: true
                            height: 50
                            color: "#f8f9fa"
                            border.color: emailField.activeFocus ? "#764ba2" : "#e9ecef"
                            border.width: 2
                            radius: 8
                            
                            RowLayout {
                                anchors.fill: parent
                                anchors.margins: 15
                                spacing: 10
                                
                                Text {
                                    text: "📧"
                                    font.pixelSize: 16
                                    color: "#7f8c8d"
                                }
                                
                                TextField {
                                    id: emailField
                                    Layout.fillWidth: true
                                    placeholderText: "请输入邮箱地址"
                                    font.pixelSize: 14
                                    color: "#2c3e50"
                                    background: Rectangle { color: "transparent" }
                                    selectByMouse: true
                                    
                                    Keys.onReturnPressed: passwordField.focus = true
                                }
                            }
                        }
                        
                        // 邮箱验证提示
                        Text {
                            text: getEmailHint()
                            font.pixelSize: 11
                            color: getEmailHintColor()
                            visible: emailField.text.length > 0
                            Layout.topMargin: -2
                        }
                    }
                    
                    // 密码输入
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 5
                        
                        Text {
                            text: "密码"
                            font.pixelSize: 14
                            color: "#34495e"
                            font.bold: true
                        }
                        
                        Rectangle {
                            Layout.fillWidth: true
                            height: 50
                            color: "#f8f9fa"
                            border.color: passwordField.activeFocus ? "#764ba2" : "#e9ecef"
                            border.width: 2
                            radius: 8
                            
                            RowLayout {
                                anchors.fill: parent
                                anchors.margins: 15
                                spacing: 10
                                
                                Text {
                                    text: "🔒"
                                    font.pixelSize: 16
                                    color: "#7f8c8d"
                                }
                                
                                TextField {
                                    id: passwordField
                                    Layout.fillWidth: true
                                    placeholderText: "至少6个字符"
                                    font.pixelSize: 14
                                    color: "#2c3e50"
                                    echoMode: showPasswordButton.checked ? TextInput.Normal : TextInput.Password
                                    background: Rectangle { color: "transparent" }
                                    selectByMouse: true
                                    
                                    Keys.onReturnPressed: confirmPasswordField.focus = true
                                }
                                
                                Button {
                                    id: showPasswordButton
                                    width: 30
                                    height: 30
                                    checkable: true
                                    background: Rectangle { color: "transparent" }
                                    
                                    contentItem: Text {
                                        text: showPasswordButton.checked ? "👁️" : "🙈"
                                        font.pixelSize: 14
                                        color: "#7f8c8d"
                                        horizontalAlignment: Text.AlignHCenter
                                        verticalAlignment: Text.AlignVCenter
                                    }
                                }
                            }
                        }
                        
                        // 密码强度提示
                        Text {
                            text: getPasswordHint()
                            font.pixelSize: 11
                            color: getPasswordHintColor()
                            visible: passwordField.text.length > 0
                            Layout.topMargin: -2
                        }
                    }
                    
                    // 确认密码输入
                    ColumnLayout {
                        Layout.fillWidth: true
                        spacing: 5
                        
                        Text {
                            text: "确认密码"
                            font.pixelSize: 14
                            color: "#34495e"
                            font.bold: true
                        }
                        
                        Rectangle {
                            Layout.fillWidth: true
                            height: 50
                            color: "#f8f9fa"
                            border.color: confirmPasswordField.activeFocus ? "#764ba2" : "#e9ecef"
                            border.width: 2
                            radius: 8
                            
                            RowLayout {
                                anchors.fill: parent
                                anchors.margins: 15
                                spacing: 10
                                
                                Text {
                                    text: "🔐"
                                    font.pixelSize: 16
                                    color: "#7f8c8d"
                                }
                                
                                TextField {
                                    id: confirmPasswordField
                                    Layout.fillWidth: true
                                    placeholderText: "再次输入密码"
                                    font.pixelSize: 14
                                    color: "#2c3e50"
                                    echoMode: showPasswordButton.checked ? TextInput.Normal : TextInput.Password
                                    background: Rectangle { color: "transparent" }
                                    selectByMouse: true
                                    
                                    Keys.onReturnPressed: performRegister()
                                }
                            }
                        }
                        
                        // 密码确认提示
                        Text {
                            text: getPasswordMatchHint()
                            font.pixelSize: 11
                            color: getPasswordMatchHintColor()
                            visible: confirmPasswordField.text.length > 0
                            Layout.topMargin: -2
                        }
                    }
                    
                    // 状态消息
                    Text {
                        text: registerPage.statusMessage
                        font.pixelSize: 12
                        color: registerPage.statusColor
                        Layout.alignment: Qt.AlignHCenter
                        visible: registerPage.statusMessage !== ""
                        wrapMode: Text.WordWrap
                        Layout.fillWidth: true
                        horizontalAlignment: Text.AlignHCenter
                    }
                    
                    // 注册按钮
                    Button {
                        id: registerButton
                        Layout.fillWidth: true
                        Layout.preferredHeight: 50
                        enabled: !registerPage.isLoading && isFormValid()
                        
                        background: Rectangle {
                            color: registerButton.enabled ? (registerButton.pressed ? "#6c5ce7" : "#764ba2") : "#bdc3c7"
                            radius: 8
                            
                            Behavior on color {
                                ColorAnimation { duration: 150 }
                            }
                        }
                        
                        contentItem: RowLayout {
                            anchors.centerIn: parent
                            spacing: 10
                            
                            // 加载动画
                            Rectangle {
                                visible: registerPage.isLoading
                                width: 20
                                height: 20
                                radius: 10
                                color: "transparent"
                                border.color: "white"
                                border.width: 2
                                
                                Rectangle {
                                    width: 6
                                    height: 6
                                    radius: 3
                                    color: "white"
                                    anchors.top: parent.top
                                    anchors.horizontalCenter: parent.horizontalCenter
                                    anchors.topMargin: 2
                                    
                                    RotationAnimation on rotation {
                                        running: registerPage.isLoading
                                        from: 0
                                        to: 360
                                        duration: 1000
                                        loops: Animation.Infinite
                                    }
                                }
                            }
                            
                            Text {
                                text: registerPage.isLoading ? "注册中..." : "注册账户"
                                font.pixelSize: 16
                                font.bold: true
                                color: "white"
                            }
                        }
                        
                        onClicked: performRegister()
                    }
                    
                    // 分割线
                    RowLayout {
                        Layout.fillWidth: true
                        Layout.topMargin: 10
                        
                        Rectangle {
                            Layout.fillWidth: true
                            height: 1
                            color: "#e9ecef"
                        }
                        
                        Text {
                            text: "或"
                            font.pixelSize: 12
                            color: "#7f8c8d"
                            Layout.leftMargin: 15
                            Layout.rightMargin: 15
                        }
                        
                        Rectangle {
                            Layout.fillWidth: true
                            height: 1
                            color: "#e9ecef"
                        }
                    }
                    
                    // 登录链接
                    Button {
                        Layout.alignment: Qt.AlignHCenter
                        Layout.topMargin: 10
                        
                        background: Rectangle { color: "transparent" }
                        hoverEnabled: true
                        
                        contentItem: Text {
                            id: loginLinkText
                            text: "已有账户？立即登录"
                            font.pixelSize: 14
                            color: "#764ba2"
                            horizontalAlignment: Text.AlignHCenter
                        }
                        
                        onHoveredChanged: {
                            loginLinkText.color = hovered ? "#6c5ce7" : "#764ba2"
                        }
                        
                        onClicked: {
                            console.log("RegisterPage: 登录链接被点击")
                            console.log("RegisterPage: emit switchToLogin for manual click")
                            registerPage.switchToLogin()
                        }
                    }
                }
            }
        }
    }
    
    // 验证函数
    function isFormValid() {
        return usernameField.text.trim().length >= 3 &&
               isValidEmail(emailField.text.trim()) &&
               passwordField.text.length >= 6 &&
               passwordField.text === confirmPasswordField.text
    }
    
    function isValidEmail(email) {
        return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
    }
    
    function isValidUsername(username) {
        return /^[a-zA-Z0-9_]+$/.test(username) && username.length >= 3 && username.length <= 20
    }
    
    // 提示信息函数
    function getUsernameHint() {
        if (usernameField.text.length === 0) return ""
        if (usernameField.text.length < 3) return "用户名至少需要3个字符"
        if (usernameField.text.length > 20) return "用户名不能超过20个字符"
        if (!isValidUsername(usernameField.text)) return "只能包含字母、数字和下划线"
        return "用户名格式正确"
    }
    
    function getUsernameHintColor() {
        if (usernameField.text.length === 0) return "#7f8c8d"
        return isValidUsername(usernameField.text) ? "#27ae60" : "#e74c3c"
    }
    
    function getEmailHint() {
        if (emailField.text.length === 0) return ""
        return isValidEmail(emailField.text) ? "邮箱格式正确" : "请输入有效的邮箱地址"
    }
    
    function getEmailHintColor() {
        if (emailField.text.length === 0) return "#7f8c8d"
        return isValidEmail(emailField.text) ? "#27ae60" : "#e74c3c"
    }
    
    function getPasswordHint() {
        if (passwordField.text.length === 0) return ""
        if (passwordField.text.length < 6) return "密码至少需要6个字符"
        return "密码长度符合要求"
    }
    
    function getPasswordHintColor() {
        if (passwordField.text.length === 0) return "#7f8c8d"
        return passwordField.text.length >= 6 ? "#27ae60" : "#e74c3c"
    }
    
    function getPasswordMatchHint() {
        if (confirmPasswordField.text.length === 0) return ""
        return passwordField.text === confirmPasswordField.text ? "密码确认正确" : "两次密码输入不一致"
    }
    
    function getPasswordMatchHintColor() {
        if (confirmPasswordField.text.length === 0) return "#7f8c8d"
        return passwordField.text === confirmPasswordField.text ? "#27ae60" : "#e74c3c"
    }
    
    // 执行注册逻辑
    function performRegister() {
        if (!isFormValid()) {
            registerPage.statusMessage = "请正确填写所有必填信息"
            registerPage.statusColor = "#e74c3c"
            statusTimer.start()
            return
        }
        
        registerPage.isLoading = true
        registerPage.statusMessage = ""
        
        // 调用AuthManager的注册方法
        authManager.registerUser(
            usernameField.text.trim(),
            emailField.text.trim(),
            passwordField.text
        )
    }
    
    // 清空表单
    function clearForm() {
        usernameField.text = ""
        emailField.text = ""
        passwordField.text = ""
        confirmPasswordField.text = ""
        registerPage.statusMessage = ""
        registerPage.isLoading = false
    }
}
